/*
 * Simplify Path
Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
 */
package com.xinpan.exercise;

import java.util.Stack;

public class SimplifyPath {
    public String simplifyPath(String path) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(path.length() == 0 || path.charAt(0) != '/')
            return null;

        Stack<String> ps = new Stack<String>();
            
        for(int i = 0; i < path.length(); )
        {
            for(; i < path.length() && path.charAt(i) == '/'; i++);
            
            String str = "";
            for(; i < path.length() && path.charAt(i) != '/'; i++)
                str += path.substring(i,i+1);
            
            if(str.length() == 0 || str.equals("."))
                continue;
            else if(str.equals(".."))
            {
                if(ps.size() != 0)
                    ps.pop();
            }
            else
                ps.push(str);
        }
        if(ps.size() == 0)
            return "/";
            
        String res = "";
        for(String str : ps)
            res += "/" + str;
        return res;
    }
}
